package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"

	"cdk.tf/go/stack/models"
	"cdk.tf/go/stack/services"
	"cdk.tf/go/stack/stacks"
	"github.com/hashicorp/terraform-cdk-go/cdktf"
)

func main() {
	// 初始化 AWS 客户端管理器
	awsClientManager := services.NewAWSClientManager()

	// 初始化服务
	ec2Service := services.NewEC2Service(awsClientManager)

	// 创建 CDKTF App
	app := cdktf.NewApp(nil)

	// 创建主堆栈
	stacks.NewMainStack(app, "ec2-management-stack", "us-west-2")

	// 启动 HTTP API 服务器
	go startHTTPServer(ec2Service, awsClientManager)

	// 合成 Terraform 配置
	app.Synth()
}

func startHTTPServer(ec2Service *services.EC2Service, awsClientManager *services.AWSClientManager) {
	http.HandleFunc("/api/ec2/create", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}

		var req models.EC2CreationRequest
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, "Invalid JSON", http.StatusBadRequest)
			return
		}

		// 转换为接口配置
		config := req.ToEC2Config()

		// 创建实例
		instance, err := ec2Service.CreateEC2Instance(nil, "api-created-instance", config)
		if err != nil {
			sendErrorResponse(w, "Failed to create instance", err)
			return
		}

		// 这里需要等待部署完成，然后获取实例信息
		response := models.EC2OperationResponse{
			Success: true,
			Message: "EC2 instance creation initiated",
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(response)
	})

	http.HandleFunc("/api/ec2/info", func(w http.ResponseWriter, r *http.Request) {
		instanceID := r.URL.Query().Get("instance_id")
		region := r.URL.Query().Get("region")
		if region == "" {
			region = "us-west-2"
		}

		if instanceID == "" {
			// 获取所有实例信息
			instances, err := ec2Service.GetAllInstancesInfo(region)
			if err != nil {
				sendErrorResponse(w, "Failed to get instances info", err)
				return
			}

			w.Header().Set("Content-Type", "application/json")
			json.NewEncoder(w).Encode(instances)
			return
		}

		// 获取特定实例信息
		instanceInfo, err := ec2Service.GetInstanceInfoAWS(instanceID, region)
		if err != nil {
			sendErrorResponse(w, "Failed to get instance info", err)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(instanceInfo)
	})

	http.HandleFunc("/api/ec2/terminate", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}

		var req struct {
			InstanceID string `json:"instance_id"`
			Region     string `json:"region"`
		}

		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, "Invalid JSON", http.StatusBadRequest)
			return
		}

		if req.Region == "" {
			req.Region = "us-west-2"
		}

		err := ec2Service.TerminateInstance(req.InstanceID, req.Region)
		if err != nil {
			sendErrorResponse(w, "Failed to terminate instance", err)
			return
		}

		response := models.EC2OperationResponse{
			Success:    true,
			Message:    "Instance termination initiated",
			InstanceID: req.InstanceID,
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(response)
	})

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	log.Printf("Starting enhanced EC2 API server on :%s", port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}

func sendErrorResponse(w http.ResponseWriter, message string, err error) {
	response := models.EC2OperationResponse{
		Success: false,
		Message: fmt.Sprintf("%s: %v", message, err),
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusInternalServerError)
	json.NewEncoder(w).Encode(response)
}
